//
// Created by Tan Ke on 2024/1/16.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
    struct ListNode* result = NULL;
    struct ListNode* resultIndex = NULL;
    int extra = 0;
    struct ListNode* l1Index = l1;
    struct ListNode* l2Index = l2;

    while (l1Index != NULL || l2Index != NULL) {
        int val = 0;
        if (l1Index != NULL && l2Index != NULL) {
            val = l1Index->val + l2Index->val + extra;
            l1Index = l1Index->next;
            l2Index = l2Index->next;
        } else if (l1Index != NULL && l2Index == NULL) {
            val = l1Index->val + extra;
            l1Index = l1Index->next;
        } else if (l1Index == NULL && l2Index != NULL) {
            val = l2Index->val + extra;
            l2Index = l2Index->next;
        }
        extra = val / 10;
        val = val % 10;

        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = val;
        node->next = NULL;

        if (resultIndex == NULL) {
            result = node;
            resultIndex = node;
        } else {
            resultIndex->next = node;
            resultIndex = node;
        }
    }

    if (extra == 1) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = 1;
        node->next = NULL;

        resultIndex->next = node;
    }

    return result;
}

int main(void)
{
    return 0;
}